package com.wangyadong.hobby.schedule.jobtask.javasync;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/11/159:23
 **/
public class IntegerAccumulator {

    private volatile int init;

    public   IntegerAccumulator(int init) {
        this.init = init;
    }

    public synchronized int add(int i) {
        this.init += i;
        return this.init;
    }

    public int getValue() {
        return this.init;
    }

    public static void main(String[] args) {
        IntegerAccumulator accumulator = new IntegerAccumulator(0);
        IntStream.range(0, 3).forEach(i -> new Thread(() -> {
            int inc = 0;
            while (true) {
                int oldValue ;
                int result  ;
//                synchronized (IntegerAccumulator.class){
                      oldValue = accumulator.getValue();
                      result = accumulator.add(i);
//                }

                System.out.println("the old value is " + oldValue + " new result " + result);
                if ((inc + oldValue) != result) {
                    System.out.println("ERROR: " + oldValue + "+ " + inc + "=" + result);
                }
                inc++;
                slowly();
            }

        }).start());
    }

    private static void slowly() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
